package packed_widgets

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/widget"
)

type menuItem struct {
	text     string
	data     interface{}
	onTapped func(interface{})
}

type MenuButton struct {
	*BaseComponent
	*widget.Button
	Items []*menuItem
}

func (btn *MenuButton) ToolbarObject() fyne.CanvasObject {
	return btn
}

func (btn *MenuButton) AddItem(text string, data interface{}, onTapped func(interface{})) {
	btn.Items = append(btn.Items, &menuItem{
		text:     text,
		data:     data,
		onTapped: onTapped,
	})
}

func (btn *MenuButton) Tapped(e *fyne.PointEvent) {
	menu := fyne.NewMenu("")
	for _, item := range btn.Items {
		menu.Items = append(menu.Items, fyne.NewMenuItem(item.text, func() {
			if item.onTapped != nil {
				item.onTapped(item.data)
			}
		}))
	}
	widget.ShowPopUpMenuAtPosition(menu, fyne.CurrentApp().Driver().CanvasForObject(btn), e.AbsolutePosition)
}

func NewMenuButton(text string, icon fyne.Resource) *MenuButton {
	btn := &MenuButton{
		BaseComponent: NewBaseComponent(),
		Button:        widget.NewButtonWithIcon(text, icon, nil),
	}

	btn.ExtendBaseWidget(btn)
	return btn
}
